"""
从 meraki-api-index.csv 读取接口索引，生成 GET 路由的 Mock 索引文件。

使用：
  .\.venv\Scripts\python generate_meraki_mocks.py e:\code_repo\pyTest\pyTest\meraki-api-index.csv

输出：
  mock_meraki_get_endpoints.json
"""

from __future__ import annotations

import csv
import json
import os
import re
import sys
from typing import List, Dict


def to_pattern(path: str) -> str:
    # 去掉前导斜杠，并将 {param} 替换为非斜杠的通配符
    sub = path.lstrip('/')
    sub = re.sub(r"\{[^}]+\}", r"[^/]+", sub)
    return rf"^{sub}$"


def build_mock_response_fields(param_list: List[str]) -> Dict[str, object]:
    mock: Dict[str, object] = {}
    for raw in param_list:
        k = raw.strip()
        if not k:
            continue
        lk = k.lower()
        if lk.endswith('id') or lk == 'id':
            mock[k] = f"{k}_123"
        elif 'count' in lk or lk.startswith('num'):
            mock[k] = 0
        elif lk in {'enabled', 'disabled'} or lk.endswith('enabled'):
            mock[k] = True
        elif lk in {'status'}:
            mock[k] = 'ok'
        elif lk in {'lat', 'lng'}:
            mock[k] = 0.0
        else:
            mock[k] = f"sample_{k}"
    return mock


def main():
    in_path = sys.argv[1] if len(sys.argv) > 1 else 'meraki-api-index.csv'
    out_path = 'mock_meraki_get_endpoints.json'
    rows: List[dict] = []
    with open(in_path, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            if row.get('method', '').lower() != 'get':
                continue
            path = row.get('path', '').strip()
            operation_id = row.get('operationId', '').strip()
            summary = row.get('summary', '').strip()
            response_params = [p for p in (row.get('responseParams', '') or '').split(',')]
            entry = {
                'method': 'get',
                'path': path,
                'pathPattern': to_pattern(path),
                'operationId': operation_id,
                'summary': summary,
                'responseParams': [p.strip() for p in response_params if p.strip()],
                'mock': build_mock_response_fields(response_params),
            }
            rows.append(entry)

    with open(out_path, 'w', encoding='utf-8') as f:
        json.dump({'basePath': '/api/v1', 'endpoints': rows}, f, ensure_ascii=False, indent=2)

    print(f"生成完成：{os.path.abspath(out_path)}，共 {len(rows)} 个 GET 接口")


if __name__ == '__main__':
    main()